<template>
  <div class="video-mix-list">
    <div class="header">
      <h1>混剪视频列表</h1>
      <div class="header-actions">
        <el-button @click="refreshList" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新状态
        </el-button>
        <el-button type="primary" @click="createNew">
          <el-icon><Plus /></el-icon>
          创建新视频
        </el-button>
      </div>
    </div>

    <!-- 状态提示 -->
    <div class="status-tip">
      <el-icon><InfoFilled /></el-icon>
      <span>视频状态不会自动更新，请点击"刷新状态"按钮查看最新进度</span>
    </div>

    <!-- 视频列表 -->
    <div class="video-grid" v-loading="loading">
      <div 
        v-for="video in videoList" 
        :key="video.id" 
        class="video-card"
        :class="{ 'disabled': video.status === 'processing' }"
      >
        <div class="video-thumbnail">
          <video
            v-if="isVideoCompleted(video) && getVideoUrl(video)"
            :src="getVideoUrl(video)"
            class="preview-video"
            preload="metadata"
            :controls="isPlaying[video.id]"
            @click.stop="toggleVideoPlay(video)"
            ref="videoRefs"
          ></video>
          <div v-else class="placeholder-thumbnail">
            <el-icon size="48"><VideoCamera /></el-icon>
          </div>
          <div class="status-badge" :class="getStatusClass(video.status)">
            {{ getStatusText(video.status) }}
          </div>
          <!-- 播放按钮覆盖层 -->
          <div 
            v-if="isVideoCompleted(video) && getVideoUrl(video) && !isPlaying[video.id]" 
            class="play-overlay"
            @click.stop="toggleVideoPlay(video)"
          >
            <el-icon size="48"><VideoPlay /></el-icon>
          </div>
        </div>
        
        <div class="video-info">
          <h3 class="video-title">{{ video.product_name || video.productName || video.taskName || video.name || '未命名' }}</h3>
          <div class="video-meta">
            <span class="create-time">{{ formatTime(video.create_time || video.createTime || video.createdAt) }}</span>
            <span v-if="video.duration" class="duration">{{ formatDuration(video.duration) }}</span>
          </div>
        </div>

        <div class="video-actions">
          <el-button 
            v-if="video.status === 'processing' || video.status === 'pending' || video.status === 1" 
            type="primary" 
            size="small"
            disabled
          >
            生成中...
          </el-button>
          <el-button 
            v-if="video.status === 'completed' || video.status === 'success' || video.status === 2" 
            type="primary" 
            size="small"
            @click.stop="handleDownload(video)"
          >
            下载视频
          </el-button>
          <el-button 
            v-if="video.status === 'failed' || video.status === 'error' || video.status === 3" 
            type="danger" 
            size="small"
            @click.stop="handleRetry(video)"
          >
            重新生成
          </el-button>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && videoList.length === 0" class="empty-state">
        <el-icon size="64"><VideoCamera /></el-icon>
        <h3>暂无视频</h3>
        <p>点击"创建新视频"开始制作您的第一个混剪视频</p>
        <el-button type="primary" @click="createNew">
          <el-icon><Plus /></el-icon>
          创建新视频
        </el-button>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 48]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, VideoCamera, VideoPlay, Refresh, InfoFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { apiRequest } from '../../config/api.js'

const router = useRouter()

// 数据
const loading = ref(false)
const videoList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)
const isPlaying = ref({})

// 获取视频列表
const getVideoList = async () => {
  loading.value = true
  try {
    console.log('请求视频列表，页码:', currentPage.value, '每页条数:', pageSize.value)
    const response = await apiRequest(`/m2v/task/list?page=${currentPage.value}&pageSize=${pageSize.value}`, {
      method: 'GET'
    })
    
    if (response && response.code === 200) {
      const { list, total: totalCount, page, page_size } = response.data
      videoList.value = list || []
      total.value = totalCount || 0
      // 同步分页信息
      currentPage.value = page || 1
      pageSize.value = page_size || 12
      console.log('获取到视频列表:', videoList.value.length, '条，总数:', total.value)
    } else {
      console.error('获取视频列表失败:', response)
      ElMessage.error(response?.msg || response?.message || '获取视频列表失败')
      videoList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取视频列表失败:', error)
    ElMessage.error('获取视频列表失败')
    videoList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

// 格式化时长
const formatDuration = (duration) => {
  if (!duration) return '-'
  const minutes = Math.floor(duration / 60)
  const seconds = duration % 60
  return `${minutes}:${seconds.toString().padStart(2, '0')}`
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    processing: '生成中',
    pending: '等待中',
    completed: '已完成',
    success: '已完成',
    failed: '生成失败',
    error: '生成失败',
    0: '处理中',
    1: '生成中',
    2: '已完成',
    3: '生成失败'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态样式类
const getStatusClass = (status) => {
  if (status === 'processing' || status === 'pending' || status === 0 || status === 1) {
    return 'processing'
  }
  if (status === 'completed' || status === 'success' || status === 2) {
    return 'completed'
  }
  if (status === 'failed' || status === 'error' || status === 3) {
    return 'failed'
  }
  return 'unknown'
}

// 判断视频是否已完成
const isVideoCompleted = (video) => {
  return video.status === 'completed' || video.status === 'success' || video.status === 2
}

// 获取视频URL
const getVideoUrl = (video) => {
  return video.video_url || video.url || video.videoUrl || video.outputUrl || video.resultUrl
}

// 切换视频播放状态
const toggleVideoPlay = (video) => {
  const videoUrl = getVideoUrl(video)
  if (!videoUrl) return
  
  if (isPlaying.value[video.id]) {
    const videoElements = document.querySelectorAll('video')
    videoElements.forEach(videoEl => {
      if (videoEl.src === videoUrl) {
        videoEl.pause()
      }
    })
    isPlaying.value[video.id] = false
  } else {
    const videoElements = document.querySelectorAll('video')
    videoElements.forEach(videoEl => {
      videoEl.pause()
    })
    Object.keys(isPlaying.value).forEach(key => {
      isPlaying.value[key] = false
    })
    
    videoElements.forEach(videoEl => {
      if (videoEl.src === videoUrl) {
        videoEl.play()
        isPlaying.value[video.id] = true
      }
    })
  }
}

// 处理下载
const handleDownload = (video) => {
  const videoUrl = getVideoUrl(video)
  if (videoUrl) {
    const link = document.createElement('a')
    link.href = videoUrl
    link.download = `${video.product_name || video.productName || video.taskName || video.name || 'video'}.mp4`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } else {
    ElMessage.warning('视频文件不可用')
  }
}

// 处理重试
const handleRetry = async (video) => {
  try {
    console.log('重试生成视频:', video.id, video.task_id)
    const response = await apiRequest(`/m2v/task/retry/${video.id}`, {
      method: 'POST'
    })
    
    if (response && response.code === 200) {
      ElMessage.success('重新生成任务已提交')
      // 重新获取列表数据
      getVideoList()
    } else {
      console.error('重试失败:', response)
      ElMessage.error(response?.msg || response?.message || '重试失败')
    }
  } catch (error) {
    console.error('重试失败:', error)
    ElMessage.error('重试失败')
  }
}

// 刷新列表
const refreshList = async () => {
  try {
    await getVideoList()
    ElMessage.success('状态已刷新')
  } catch (error) {
    console.error('刷新失败:', error)
    ElMessage.error('刷新失败，请重试')
  }
}

// 创建新视频
const createNew = () => {
  router.push('/video-mix/generate')
}

// 分页相关
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  getVideoList()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  getVideoList()
}

// 页面加载时获取数据
onMounted(() => {
  getVideoList()
})
</script>

<style scoped>
.video-mix-list {
  min-height: 100vh;
  background: #18181c;
  padding: 24px;
  color: #909399;

  .status-tip {
    display: flex;
    align-items: center;
    gap: 8px;
    background: linear-gradient(135deg, #409eff, #66b1ff);
    color: white;
    padding: 12px 16px;
    border-radius: 8px;
    margin-bottom: 24px;
    font-size: 14px;
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);

    .el-icon {
      font-size: 16px;
    }
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}

.header h1 {
  margin: 0;
  font-size: 28px;
  font-weight: 600;
  color: #909399;
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.video-card {
  background: #23232a;
  border-radius: 16px;
  overflow: hidden;
  transition: all 0.3s ease;
  border: 1px solid #2a2a2a;
  cursor: pointer;
}

.video-card:hover {
  transform: translateY(-4px);
  border-color: #409eff;
  box-shadow: 0 8px 32px rgba(64, 158, 255, 0.2);
}

.video-card.disabled {
  cursor: not-allowed;
  opacity: 0.8;
}

.video-card.disabled:hover {
  transform: none;
  border-color: #2a2a2a;
  box-shadow: none;
}

.video-thumbnail {
  position: relative;
  width: 100%;
  height: 200px;
  background: #18181c;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.video-thumbnail video {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background: #000;
}

.placeholder-thumbnail {
  color: #909399;
}

.status-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.processing {
  background: rgba(230, 162, 60, 0.9);
  color: #18181c;
}

.status-badge.completed {
  background: rgba(103, 194, 58, 0.9);
  color: #18181c;
}

.status-badge.failed {
  background: rgba(245, 108, 108, 0.9);
  color: #18181c;
}

.play-overlay {
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.video-thumbnail:hover .play-overlay {
  opacity: 1;
}

.play-overlay .el-icon {
  color: #fff;
  font-size: 48px;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.5));
}

.video-info {
  padding: 16px;
}

.video-title {
  font-size: 16px;
  font-weight: 600;
  color: #909399;
  margin: 0 0 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.video-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #606266;
}

.video-actions {
  padding: 12px 16px;
  border-top: 1px solid #2a2a2a;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 80px 20px;
  color: #909399;
}

.empty-state h3 {
  margin: 16px 0 8px;
  font-size: 18px;
  color: #909399;
}

.empty-state p {
  margin: 0 0 24px;
  font-size: 14px;
  color: #606266;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

/* Element Plus 暗色主题覆盖 */
:deep(.el-button) {
  background: #23232a !important;
  border-color: #333 !important;
  color: #909399 !important;
}

:deep(.el-button:hover) {
  background: #2a2a2a !important;
  border-color: #409eff !important;
  color: #409eff !important;
}

:deep(.el-button--primary) {
  background: #409eff !important;
  border-color: #409eff !important;
  color: #18181c !important;
}

:deep(.el-button--primary:hover) {
  background: #66b1ff !important;
  border-color: #66b1ff !important;
}

:deep(.el-button--danger) {
  background: #f56c6c !important;
  border-color: #f56c6c !important;
  color: #18181c !important;
}

:deep(.el-button--danger:hover) {
  background: #f78989 !important;
  border-color: #f78989 !important;
}

:deep(.el-pagination) {
  --el-pagination-bg-color: #23232a;
  --el-pagination-hover-color: #409eff;
  --el-text-color-regular: #909399;
  --el-disabled-bg-color: #2a2a2a;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  background: #23232a !important;
  color: #909399 !important;
}

:deep(.el-pagination .el-pager li) {
  background: #23232a !important;
  color: #909399 !important;
  border: 1px solid #333 !important;
}

:deep(.el-pagination .el-pager li:hover) {
  color: #409eff !important;
}

:deep(.el-pagination .el-pager li.is-active) {
  background: #409eff !important;
  color: #18181c !important;
  border-color: #409eff !important;
}

:deep(.el-pagination .el-pagination__total),
:deep(.el-pagination .el-pagination__jump) {
  color: #909399 !important;
}

:deep(.el-pagination .el-input__wrapper) {
  background: #23232a !important;
  box-shadow: 0 0 0 1px #333 inset !important;
}

:deep(.el-pagination .el-input__inner) {
  color: #909399 !important;
}

:deep(.el-select-dropdown) {
  background: #23232a !important;
  border: 1px solid #333 !important;
}

:deep(.el-select-dropdown__item) {
  color: #909399 !important;
}

:deep(.el-select-dropdown__item.hover) {
  background: #2a2a2a !important;
}

:deep(.el-select-dropdown__item.selected) {
  background: #2a2a2a !important;
  color: #409eff !important;
}

/* 每页数量选择器样式 - 加强覆盖 */
:deep(.el-pagination .el-select) {
  background: #23232a !important;
}

:deep(.el-pagination .el-select .el-input) {
  background: #23232a !important;
}

:deep(.el-pagination .el-select .el-input__wrapper) {
  background: #23232a !important;
  box-shadow: 0 0 0 1px #333 !important;
  border: 1px solid #333 !important;
}

:deep(.el-pagination .el-select .el-input__inner) {
  background: #23232a !important;
  color: #909399 !important;
  border: none !important;
}

:deep(.el-pagination .el-select .el-select__caret) {
  color: #909399 !important;
}

/* 针对每页数量选择的下拉框 */
:deep(.el-pagination__sizes .el-select) {
  background: #23232a !important;
}

:deep(.el-pagination__sizes .el-select .el-input__wrapper) {
  background: #23232a !important;
  box-shadow: 0 0 0 1px #333 !important;
}

:deep(.el-pagination__sizes .el-select .el-input__inner) {
  background: #23232a !important;
  color: #909399 !important;
}

/* 强制覆盖所有分页组件内的选择器背景 */
:deep(.pagination .el-select),
:deep(.pagination .el-select *),
:deep(.el-pagination .el-select),
:deep(.el-pagination .el-select *) {
  background: #23232a !important;
  background-color: #23232a !important;
  color: #909399 !important;
}

/* 强制覆盖所有输入框背景 */
:deep(.pagination .el-input),
:deep(.pagination .el-input *),
:deep(.el-pagination .el-input),
:deep(.el-pagination .el-input *) {
  background: #23232a !important;
  background-color: #23232a !important;
  color: #909399 !important;
}

/* 最强力覆盖 - 包括所有状态 */
:deep(.el-pagination) input,
:deep(.el-pagination) input:focus,
:deep(.el-pagination) input:hover,
:deep(.el-pagination) .el-input__inner,
:deep(.el-pagination) .el-input__wrapper,
:deep(.el-pagination) .el-select,
:deep(.el-pagination) .el-select .el-input,
:deep(.el-pagination) .el-select .el-input__inner,
:deep(.el-pagination) .el-select .el-input__wrapper {
  background: #23232a !important;
  background-color: #23232a !important;
  color: #909399 !important;
  border-color: #333 !important;
}

/* 移除分页组件的白色边框 */
:deep(.el-pagination .el-pager li) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}

:deep(.el-pagination .el-input__wrapper) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}

:deep(.el-pagination .el-select .el-input__wrapper) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}

:deep(.el-pagination__sizes .el-select .el-input__wrapper) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}

:deep(.el-pagination) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}

:deep(.pagination) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}

/* 全面覆盖所有分页相关元素的边框 */
:deep(.el-pagination *) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}

:deep(.pagination *) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}
</style> 